namespace Backoffice.Application.Services;


using Backoffice.Application.Common.Interfaces;
using Backoffice.Application.DTOs;
using Backoffice.Domain.Entities.App;
using Backoffice.Domain.Repositories;


public class UserService
{
    private readonly IRepository<AppUser> _repo;
    private readonly ICurrentUser _currentUser;
    private readonly IPasswordHasher _passwordHasher;

    

    public UserService(IRepository<AppUser> repo, ICurrentUser currentUser, IPasswordHasher passwordHasher)
    {
        _repo = repo;
        _currentUser = currentUser;
        _passwordHasher = passwordHasher;
    }

    public async Task<AppUser?> GetCurrentUserAsync()
    {
        var userId = _currentUser.UserId;
        return await _repo.GetByIdAsync(userId);
    }

    public async Task UpdateUserInfoAsync(UserDto dto)
    {
        var user = await GetCurrentUserAsync();
        if (user == null)
            throw new Exception("用户未找到");

#pragma warning disable CS8604 // 引用类型参数可能为 null。
        user.UpdateInfo(dto.Name, dto.Email, dto.Phone);
#pragma warning restore CS8604 // 引用类型参数可能为 null。
        await _repo.UpdateAsync(user);
    }
    public async Task ChangePasswordAsync(string currentPassword, string newPassword)
    {
        var user = await GetCurrentUserAsync();
        if (user == null)
            throw new Exception("用户未找到");

        // 验证当前密码
        if (!_passwordHasher.VerifyHashedPassword(user.PasswordHash, currentPassword))
            throw new Exception("当前密码不正确");

        // 加密新密码
        var newPasswordHash = _passwordHasher.HashPassword(newPassword);
        user.ChangePassword(newPasswordHash);
        await _repo.UpdateAsync(user);
    }

    public async Task AssignRoleAsync(AppRole role)
    {
        var user = await GetCurrentUserAsync();
        if (user == null)
            throw new Exception("用户未找到");

        user.AssignRole(role);
        await _repo.UpdateAsync(user);
    }

    public async Task RemoveRoleAsync(Guid roleId)
    {
        var user = await GetCurrentUserAsync();
        if (user == null)
            throw new Exception("用户未找到");

        user.RemoveRole(roleId);
        await _repo.UpdateAsync(user);
    }

    // 创建用户
    public async Task<AppUser> CreateUserAsync(CreateUserDto dto)
    {
        // 检查用户名是否已存在
        var existingUser = await _repo.GetAllAsync();
        if (existingUser.Any(u => u.Username == dto.Username))
            throw new Exception("用户名已存在");

        // 检查邮箱是否已存在
        if (existingUser.Any(u => u.Email == dto.Email))
            throw new Exception("邮箱已存在");

        // 加密密码
        var passwordHash = _passwordHasher.HashPassword(dto.Password);

        // 创建新用户
        var user = new AppUser(dto.Username, passwordHash, dto.Email, dto.Phone ?? string.Empty);
        
        return await _repo.CreateAsync(user);
    }

    // 更新用户
    public async Task<AppUser> UpdateUserAsync(UpdateUserDto dto)
    {
        var user = await _repo.GetByIdAsync(dto.Id);
        if (user == null)
            throw new Exception("用户未找到");

        // 检查用户名是否已被其他用户使用
        var existingUsers = await _repo.GetAllAsync();
        if (existingUsers.Any(u => u.Username == dto.Username && u.Id != dto.Id))
            throw new Exception("用户名已存在");

        // 检查邮箱是否已被其他用户使用
        if (existingUsers.Any(u => u.Email == dto.Email && u.Id != dto.Id))
            throw new Exception("邮箱已存在");

        // 更新用户信息
        user.UpdateInfo(dto.Username, dto.Email, dto.Phone ?? string.Empty);
        
        await _repo.UpdateAsync(user);
        return user;
    }

    // 删除用户
    public async Task DeleteUserAsync(Guid userId)
    {
        var user = await _repo.GetByIdAsync(userId);
        if (user == null)
            throw new Exception("用户未找到");

        await _repo.DeleteAsync(userId);
    }

    // 根据ID获取用户
    public async Task<AppUser?> GetUserByIdAsync(Guid userId)
    {
        return await _repo.GetByIdAsync(userId);
    }

    //用户树
    public async Task<List<UserTreeDto>> GetUserTreeAsync()
{
    var users = await _repo.GetAllAsync();
    var userTree = BuildUserTree(users);
    return userTree;
}

private List<UserTreeDto> BuildUserTree(IEnumerable<AppUser> users)
{
    var userTree = users
        .Select(u => new UserTreeDto
        {
            Id = u.Id,
            Username = u.Username,
            Email = u.Email,
            Phone = u.Phone,
            Name = u.Username, // 使用Username作为显示名称
            Department = "技术部", // 默认部门，实际应该从用户角色获取
            Role = "开发工程师", // 默认角色，实际应该从用户角色获取
            Status = "在职", // 默认状态
            Children = new List<UserTreeDto>() // 暂时不实现层级结构
        })
        .ToList();

    return userTree ?? [];
}
}

